package com.wp.admin.service.impl;

import com.wp.admin.mapper.SysDeptMapper;
import com.wp.admin.pojo.SysDept;
import com.wp.admin.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wp
 * @create 2019-03-03 15:48
 */
@Service
@Transactional
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public List<SysDept> findDeptByIds(List<Long> deptIds) {
        return sysDeptMapper.selectByIdList(deptIds);
    }

    @Override
    public List<SysDept> findTree() {
        List<SysDept> sysDepts = sysDeptMapper.selectAll();
        List<SysDept> parentDepts = sysDepts.stream().filter(sysDept -> sysDept.getParentId() == null || sysDept.getParentId() == 0).collect(Collectors.toList());
        findChildren(parentDepts, sysDepts);
        return parentDepts;
    }

    private void findChildren(List<SysDept> parentDepts, List<SysDept> sysDepts) {
        for (SysDept parentDept : parentDepts) {
            List<SysDept> childrenDepts = sysDepts.stream().filter(sysDept -> sysDept.getId() != null && sysDept.getParentId().equals(parentDept.getId())).collect(Collectors.toList());
            parentDept.setChildren(childrenDepts);
            findChildren(childrenDepts, sysDepts);
        }
    }
}
